package chances.wechat.utils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONUtils {
	static ObjectMapper objectMapper = new ObjectMapper();

	public static String fromObject(Object obj) {
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			return "{}";
		}
	}
	
	
	public static Map<String,Object> toMap(String json) {

		try {
			return objectMapper.readValue(json,new TypeReference<Map<String,Object>>(){});
		} catch (IOException e) {
			return null;
		}

	}
	
	public static List<Map<String,Object>> toArray(String json) {

		try {
			return objectMapper.readValue(json,new TypeReference<List<Map<String,Object>>>(){});
		} catch (IOException e) {
			return null;
		}

	}

	public static <T> T toObject(String json, Class<T> clazz) {

		try {
			return objectMapper.readValue(json, clazz);
		} catch (IOException e) {
			return null;
		}

	}
	
	public static <T> T toObject(String json, TypeReference<T> typeref) {

		try {
			return objectMapper.readValue(json, typeref);
		} catch (IOException e) {
			return null;
		}

	}

}
